(() => {
    // DOM元素
    const elements = {
        menuToggle: document.getElementById('menuToggle'),
        adminSidebar: document.getElementById('adminSidebar'),
        navItems: document.querySelectorAll('.nav-item'),
        sections: document.querySelectorAll('.content-section'),
        pageTitle: document.querySelector('.page-title'),
        dbStatus: document.getElementById('dbStatus'),
        settingsForm: document.getElementById('settingsForm'),
        securityForm: document.getElementById('securityForm'),
        historyFilter: document.getElementById('historyFilter'),
        historyList: document.getElementById('historyList'),
        refreshHistoryBtn: document.getElementById('refreshHistoryBtn'),
        testPushBtn: document.getElementById('testPushBtn'),
        todayCount: document.getElementById('todayCount'),
        totalCount: document.getElementById('totalCount'),
        lastNotifyTime: document.getElementById('lastNotifyTime'),
        toastContainer: document.getElementById('toastContainer'),
        overlay: document.querySelector('.sidebar-overlay'),
        mainContent: document.querySelector('.admin-main'),
        // 表单输入
        phoneInput: document.getElementById('phoneInput'),
        cooldownInput: document.getElementById('cooldownInput'),
        defaultMessageInput: document.getElementById('defaultMessageInput'),
        apiUrlInput: document.getElementById('apiUrlInput'),
        appTokenInput: document.getElementById('appTokenInput'),
        uidInput: document.getElementById('uidInput'),
        currentPassword: document.getElementById('currentPassword'),
        newPassword: document.getElementById('newPassword'),
        confirmPassword: document.getElementById('confirmPassword')
    };

    // 状态管理
    const state = {
        config: null,
        stats: null,
        notifications: [],
        dbConnected: false,
        sidebarOpen: false,
        isMobile: window.innerWidth <= 768,
        lastNotifyTime: 0
    };

    // Toast提示
    async function showToast(message, type = 'info') {
        const toast = elements.toastContainer;
        const text = toast.querySelector('.toast-message');
        
        text.textContent = message;
        toast.classList.add('show');
        
        if (type !== 'loading') {
            setTimeout(() => {
                toast.classList.remove('show');
            }, 2000);
        }
    }

    // 检查数据库连接
    async function checkDatabase() {
        try {
            const response = await fetch('db_check.php');
            const data = await response.json();
            
            const statusDot = elements.dbStatus.querySelector('.status-dot');
            const statusText = elements.dbStatus.querySelector('.status-text');
            
            if (data.success) {
                statusDot.className = 'status-dot connected';
                statusText.textContent = '连接正常';
                state.dbConnected = true;
            } else {
                throw new Error(data.error);
            }
        } catch (error) {
            elements.dbStatus.querySelector('.status-dot').className = 'status-dot error';
            elements.dbStatus.querySelector('.status-text').textContent = '连接失败';
            state.dbConnected = false;
            console.error('数据库检查失败:', error);
        }
    }

    // 加载配置
    async function loadConfig() {
        try {
            const response = await fetch('api.php?action=getConfig');
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            state.config = data.data;
            updateConfigUI();
        } catch (error) {
            console.error('加载配置失败:', error);
            await showToast('加载配置失败', 'error');
        }
    }

    // 更新配置UI
    function updateConfigUI() {
        if (!state.config) return;

        elements.phoneInput.value = state.config.phone || '';
        elements.cooldownInput.value = (state.config.notification.cooldown || 120000) / 1000;
        elements.defaultMessageInput.value = state.config.notification.defaultMessage || '';
        elements.apiUrlInput.value = state.config.wxPusher.apiUrl || '';
        elements.appTokenInput.value = state.config.wxPusher.appToken || '';
        elements.uidInput.value = state.config.wxPusher.uids[0] || '';
    }

    // 保存配置
    async function saveConfig(event) {
        event.preventDefault();
        
        try {
            const phone = elements.phoneInput.value.trim();
            const cooldown = parseInt(elements.cooldownInput.value) * 1000;
            const defaultMessage = elements.defaultMessageInput.value.trim();
            const appToken = elements.appTokenInput.value.trim();
            const uid = elements.uidInput.value.trim();
            const apiUrl = elements.apiUrlInput.value.trim();

            if (!phone) throw new Error('请输入电话号码');
            if (isNaN(cooldown) || cooldown < 1000) throw new Error('请输入有效的冷却时间');
            if (!defaultMessage) throw new Error('请输入默认通知消息');
            if (!appToken) throw new Error('请输入AppToken');
            if (!uid) throw new Error('请输入UID');
            if (!apiUrl) throw new Error('请输入API接口地址');

            await showToast('正在保存...', 'loading');

            const response = await fetch('api.php?action=saveConfig', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    phone,
                    notification: {
                        cooldown,
                        defaultMessage
                    },
                    wxPusher: {
                        appToken,
                        uids: [uid],
                        apiUrl
                    }
                })
            });

            const data = await response.json();
            if (!data.success) throw new Error(data.error);

            await showToast('保存成功', 'success');
            await loadConfig();
        } catch (error) {
            console.error('保存失败:', error);
            await showToast(error.message || '保存失败', 'error');
        }
    }

    // 修改密码
    async function changePassword(event) {
        event.preventDefault();
        
        try {
            const currentPassword = elements.currentPassword.value;
            const newPassword = elements.newPassword.value;
            const confirmPassword = elements.confirmPassword.value;

            if (!currentPassword) throw new Error('请输入当前密码');
            if (!newPassword) throw new Error('请输入新密码');
            if (newPassword !== confirmPassword) throw new Error('两次输入的密码不一致');

            await showToast('正在修改...', 'loading');

            const response = await fetch('api.php?action=changePassword', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    currentPassword,
                    newPassword
                })
            });

            const data = await response.json();
            if (!data.success) throw new Error(data.error);

            elements.currentPassword.value = '';
            elements.newPassword.value = '';
            elements.confirmPassword.value = '';

            await showToast('密码修改成功', 'success');
        } catch (error) {
            console.error('修改密码失败:', error);
            await showToast(error.message || '修改失败', 'error');
        }
    }

    // 加载统计数据
    async function loadStats() {
        try {
            const response = await fetch('api.php?action=getStats');
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            state.stats = data.data;
            updateStatsUI();
        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    // 更新统计UI
    function updateStatsUI() {
        if (!state.stats) return;

        elements.todayCount.textContent = state.stats.today;
        elements.totalCount.textContent = state.stats.total;
    }

    // 加载历史记录
    async function loadHistory() {
        try {
            const response = await fetch('api.php?action=getNotifications');
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            state.notifications = data.data;
            updateHistoryUI();
        } catch (error) {
            console.error('加载历史记录失败:', error);
            await showToast('加载历史记录失败', 'error');
        }
    }

    // 更新历史记录UI
    function updateHistoryUI() {
        const filter = elements.historyFilter.value;
        let notifications = state.notifications;

        if (filter === 'today') {
            const today = new Date().toISOString().split('T')[0];
            notifications = notifications.filter(n => 
                n.timestamp.startsWith(today)
            );
        } else if (filter === 'week') {
            const weekAgo = new Date();
            weekAgo.setDate(weekAgo.getDate() - 7);
            notifications = notifications.filter(n => 
                new Date(n.timestamp) >= weekAgo
            );
        }

        elements.historyList.innerHTML = notifications.length === 0 
            ? '<div class="empty-state">暂无通知记录</div>'
            : notifications.map(notification => `
                <div class="history-item" data-id="${notification.id}">
                    <div class="history-content">
                        <div class="history-message">${notification.message}</div>
                        <div class="history-time">
                            ${new Date(notification.timestamp).toLocaleString()}
                        </div>
                    </div>
                    <div class="history-actions">
                        <button class="delete-btn" onclick="deleteNotification(${notification.id})">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </div>
                </div>
            `).join('');

        if (notifications.length > 0) {
            elements.lastNotifyTime.textContent = new Date(
                notifications[0].timestamp
            ).toLocaleString();
        }
    }

    // 删除通知记录
    async function deleteNotification(id) {
        try {
            const response = await fetch(`api.php?action=deleteNotification&id=${id}`, {
                method: 'DELETE'
            });
            
            const data = await response.json();
            if (!data.success) throw new Error(data.error);
            
            await loadHistory();
            await loadStats();
            await showToast('删除成功', 'success');
        } catch (error) {
            console.error('删除失败:', error);
            await showToast('删除失败', 'error');
        }
    }

    // 发送测试消息
    async function sendTestMessage() {
        try {
            await showToast('正在发送测试消息...', 'loading');

            const response = await fetch('api.php?action=testNotification');
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);

            await showToast('测试消息发送成功', 'success');
            await loadStats();
        } catch (error) {
            console.error('发送测试消息失败:', error);
            await showToast(error.message || '发送失败', 'error');
        }
    }

    // 切换侧边栏
    function toggleSidebar(show) {
        state.sidebarOpen = show === undefined ? !state.sidebarOpen : show;
        elements.adminSidebar.classList.toggle('show', state.sidebarOpen);
        elements.overlay.classList.toggle('show', state.sidebarOpen);
        document.body.classList.toggle('sidebar-open', state.sidebarOpen);
        elements.mainContent.classList.toggle('shifted', state.sidebarOpen);
    }

    // 导航切换
    function switchSection(sectionId) {
        elements.navItems.forEach(item => {
            item.classList.toggle('active', item.getAttribute('data-section') === sectionId);
        });

        elements.sections.forEach(section => {
            section.classList.toggle('active', section.id === sectionId);
        });

        elements.pageTitle.textContent = elements.navItems.find(
            item => item.getAttribute('data-section') === sectionId
        ).querySelector('span').textContent;

        if (state.isMobile) {
            toggleSidebar(false);
        }
    }

    // 初始化
    async function init() {
        // 检查数据库
        await checkDatabase();
        if (!state.dbConnected) return;

        // 加载数据
        await Promise.all([
            loadConfig(),
            loadStats(),
            loadHistory()
        ]);

        // 导航切换
        elements.navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                switchSection(item.getAttribute('data-section'));
            });
        });

        // 移动端菜单
        elements.menuToggle.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleSidebar();
        });

        // 遮罩层点击关闭侧边栏
        elements.overlay.addEventListener('click', () => {
            toggleSidebar(false);
        });

        // 点击内容区域时关闭侧边栏
        elements.mainContent.addEventListener('click', () => {
            if (state.sidebarOpen && state.isMobile) {
                toggleSidebar(false);
            }
        });

        // 表单提交
        elements.settingsForm.addEventListener('submit', saveConfig);
        elements.securityForm.addEventListener('submit', changePassword);

        // 历史记录筛选
        elements.historyFilter.addEventListener('change', updateHistoryUI);
        elements.refreshHistoryBtn.addEventListener('click', loadHistory);

        // 测试按钮
        elements.testPushBtn.addEventListener('click', sendTestMessage);

        // 添加触摸滑动支持
        let touchStartX = 0;
        let touchStartY = 0;

        document.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        }, { passive: true });

        document.addEventListener('touchmove', (e) => {
            if (!state.isMobile) return;

            const touchX = e.touches[0].clientX;
            const touchY = e.touches[0].clientY;
            const deltaX = touchX - touchStartX;
            const deltaY = touchY - touchStartY;

            // 如果水平滑动距离大于垂直滑动距离
            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                // 从左向右滑动打开菜单
                if (deltaX > 50 && touchStartX < 30 && !state.sidebarOpen) {
                    toggleSidebar(true);
                }
                // 从右向左滑动关闭菜单
                else if (deltaX < -50 && state.sidebarOpen) {
                    toggleSidebar(false);
                }
            }
        }, { passive: true });

        // 窗口大小变化
        window.addEventListener('resize', () => {
            state.isMobile = window.innerWidth <= 768;
            if (!state.isMobile && state.sidebarOpen) {
                toggleSidebar(false);
            }
        });

        // 定时刷新
        setInterval(() => {
            loadStats();
            loadHistory();
        }, 60000);
    }

    // 暴露删除方法到全局
    window.deleteNotification = deleteNotification;

    init();
})();